document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirmPassword');
    const requirements = {
        length: document.getElementById('length'),
        uppercase: document.getElementById('uppercase'),
        lowercase: document.getElementById('lowercase'),
        number: document.getElementById('number'),
        special: document.getElementById('special'),
        match: document.getElementById('match')
    };

    // 密码强度验证
    function validatePassword() {
        const pwd = password.value;
        const confirmPwd = confirmPassword.value;
        
        // 长度验证
        if(pwd.length >= 8) {
            requirements.length.classList.add('valid');
            requirements.length.classList.remove('invalid');
        } else {
            requirements.length.classList.add('invalid');
            requirements.length.classList.remove('valid');
        }
        
        // 大写字母验证
        if(/[A-Z]/.test(pwd)) {
            requirements.uppercase.classList.add('valid');
            requirements.uppercase.classList.remove('invalid');
        } else {
            requirements.uppercase.classList.add('invalid');
            requirements.uppercase.classList.remove('valid');
        }
        
        // 小写字母验证
        if(/[a-z]/.test(pwd)) {
            requirements.lowercase.classList.add('valid');
            requirements.lowercase.classList.remove('invalid');
        } else {
            requirements.lowercase.classList.add('invalid');
            requirements.lowercase.classList.remove('valid');
        }
        
        // 数字验证
        if(/[0-9]/.test(pwd)) {
            requirements.number.classList.add('valid');
            requirements.number.classList.remove('invalid');
        } else {
            requirements.number.classList.add('invalid');
            requirements.number.classList.remove('valid');
        }
        
        // 特殊字符验证
        if(/[!@#$%^&*]/.test(pwd)) {
            requirements.special.classList.add('valid');
            requirements.special.classList.remove('invalid');
        } else {
            requirements.special.classList.add('invalid');
            requirements.special.classList.remove('valid');
        }
        
        // 密码匹配验证
        if(pwd === confirmPwd && pwd !== '') {
            requirements.match.classList.add('valid');
            requirements.match.classList.remove('invalid');
        } else {
            requirements.match.classList.add('invalid');
            requirements.match.classList.remove('valid');
        }
    }

    // 监听密码输入
    password.addEventListener('input', validatePassword);
    confirmPassword.addEventListener('input', validatePassword);

    // 表单提交验证
    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        console.log('注册表单提交');
        
        const username = document.getElementById('username').value;
        const role = document.getElementById('role').value;
        
        // 验证所有密码要求是否满足
        const allRequirementsMet = Object.values(requirements).every(
            req => req.classList.contains('valid')
        );
        
        if (!username || !role) {
            showAlert('请填写所有必填字段！', 'danger');
            return;
        }
        
        if (!allRequirementsMet) {
            showAlert('请确保满足所有密码要求！', 'danger');
            return;
        }
        
        // 调用后端注册API
        showAlert('注册处理中...', 'info');
        
        fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password.value,
                role: role.toUpperCase()
            })
        })
        .then(response => {
            console.log('服务器响应状态：', response.status);
            return response.json().catch(error => {
                console.error('解析响应JSON失败：', error);
                throw new Error('服务器响应格式错误');
            });
        })
        .then(data => {
            console.log('服务器响应数据：', data);
            if (data.success) {
                showAlert('注册成功！即将跳转到登录页面...', 'success');
                setTimeout(() => {
                    window.location.href = '/login.html?registerSuccess=true';
                }, 2000);
            } else {
                showAlert(data.message || '注册失败！', 'danger');
            }
        })
        .catch(error => {
            console.error('注册请求失败：', error);
            showAlert('注册失败，请稍后重试！', 'danger');
        });
    });
    
    // 密码显示切换
    const togglePassword = document.querySelectorAll('.toggle-password');
    togglePassword.forEach(toggle => {
        toggle.addEventListener('click', function() {
            const input = this.closest('.input-group').querySelector('input');
            const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
            input.setAttribute('type', type);
            this.classList.toggle('fa-eye');
            this.classList.toggle('fa-eye-slash');
        });
    });
    
    // 角色选择变化时更新图标
    const roleSelect = document.getElementById('role');
    const roleIcon = document.querySelector('.role-icon');
    
    roleSelect.addEventListener('change', function() {
        const role = this.value;
        switch(role) {
            case 'admin':
                roleIcon.className = 'fas fa-user-shield role-icon';
                break;
            case 'meter_reader':
                roleIcon.className = 'fas fa-clipboard-list role-icon';
                break;
            case 'customer':
                roleIcon.className = 'fas fa-user role-icon';
                break;
            default:
                roleIcon.className = 'fas fa-user role-icon';
        }
    });
});

// 显示提示信息
function showAlert(message, type) {
    const alertBox = document.querySelector('.alert');
    alertBox.textContent = message;
    alertBox.className = `alert alert-${type} animated fadeIn`;
    alertBox.style.display = 'block';
    
    if (type === 'success' || type === 'danger') {
        setTimeout(() => {
            alertBox.style.display = 'none';
        }, 3000);
    }
} 